using System;
using System.Globalization;
using System.Security.Principal;
using System.Web.Mvc;
using System.Web.Security;
using ilanver.Web.Controllers.Backoffice.Plugin;

namespace ilanver.Web.Controllers.Backoffice
{
    [HandleError]
    public class AccountController : Controller
    {
       

        public ActionResult LogOn()
        {
            return this.View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(string txtUsername, string txtPassword, string returnUrl)
        {
            //if (!ValidateLogOn(txtUsername, txtPassword))
            //{
            //    return new AjaxResult { ErrorMessage = "Incorrect Username or Password" };
            //}

            ////this.FormsAuth.SignIn(txtUsername, true);

            //if (!String.IsNullOrEmpty(returnUrl))
            //{
            //    return this.Redirect(returnUrl.Replace("default.aspx", ""));
            //}

            return this.RedirectToAction("Index", "Home");
        }

        public ActionResult Logout()
        {
            //this.FormsAuth.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {

            //this.ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            return this.View();
        }

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult Register(string userName, string email, string password, string confirmPassword)
        //{

        //    this.ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;

        //    if (this.ValidateRegistration(userName, email, password, confirmPassword))
        //    {
        //        // Attempt to register the user
        //        MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);

        //        if (createStatus == MembershipCreateStatus.Success)
        //        {
        //            this.FormsAuth.SignIn(userName, false /* createPersistentCookie */);
        //            return RedirectToAction("Index", "Home");
        //        }
        //        else
        //        {
        //            this.ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return this.View();
        //}

        [Authorize]
        public ActionResult ChangePassword()
        {
            //this.ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return this.View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Exceptions result in password not being changed.")]
        public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {

            //this.ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            //if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword))
            //{
                return this.View();
            //}

            //try
            //{
            //    if (MembershipService.ChangePassword(User.Identity.Name, currentPassword, newPassword))
            //    {
            //        return RedirectToAction("ChangePasswordSuccess");
            //    }
            //    else
            //    {
            //        this.ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid.");
            //        return this.View();
            //    }
            //}
            //catch
            //{
            //    this.ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid.");
            //    return this.View();
            //}
        }

        public ActionResult ChangePasswordSuccess()
        {
            return this.View();
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
        }

        #region Validation Methods

        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            if (String.IsNullOrEmpty(currentPassword))
            {
                this.ModelState.AddModelError("currentPassword", "You must specify a current password.");
            }
            //if (newPassword == null || newPassword.Length < MembershipService.MinPasswordLength)
            //{
            //    this.ModelState.AddModelError("newPassword",
            //        String.Format(CultureInfo.CurrentCulture,
            //             "You must specify a new password of {0} or more characters.",
            //             MembershipService.MinPasswordLength));
            //}

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                this.ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }

            return this.ModelState.IsValid;
        }

        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
            {
                this.ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(password))
            {
                this.ModelState.AddModelError("password", "You must specify a password.");
            }
            //if (!MembershipService.ValidateUser(userName, password))
            //{
            //    this.ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
            //}

            return this.ModelState.IsValid;
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword)
        {
            if (String.IsNullOrEmpty(userName))
            {
                this.ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(email))
            {
                this.ModelState.AddModelError("email", "You must specify an email address.");
            }
            //if (password == null || password.Length < MembershipService.MinPasswordLength)
            //{
            //    this.ModelState.AddModelError("password",
            //        String.Format(CultureInfo.CurrentCulture,
            //             "You must specify a password of {0} or more characters.",
            //             MembershipService.MinPasswordLength));
            //}
            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
            {
                this.ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }
            return this.ModelState.IsValid;
        }

        //private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        //{
        //    // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
        //    // a full list of status codes.
        //    switch (createStatus)
        //    {
        //        case MembershipCreateStatus.DuplicateUserName:
        //            return "Username already exists. Please enter a different user name.";

        //        case MembershipCreateStatus.DuplicateEmail:
        //            return "A username for that e-mail address already exists. Please enter a different e-mail address.";

        //        case MembershipCreateStatus.InvalidPassword:
        //            return "The password provided is invalid. Please enter a valid password value.";

        //        case MembershipCreateStatus.InvalidEmail:
        //            return "The e-mail address provided is invalid. Please check the value and try again.";

        //        case MembershipCreateStatus.InvalidAnswer:
        //            return "The password retrieval answer provided is invalid. Please check the value and try again.";

        //        case MembershipCreateStatus.InvalidQuestion:
        //            return "The password retrieval question provided is invalid. Please check the value and try again.";

        //        case MembershipCreateStatus.InvalidUserName:
        //            return "The user name provided is invalid. Please check the value and try again.";

        //        case MembershipCreateStatus.ProviderError:
        //            return "The authentication this.provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

        //        case MembershipCreateStatus.UserRejected:
        //            return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

        //        default:
        //            return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
        //    }
        //}
        #endregion
    }
}
